package com.wetao.trackscreendemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.forward.androids.utils.LogUtil;
import cn.hzw.doodle.DoodleOnTouchGestureListener;
import cn.hzw.doodle.DoodleParams;
import cn.hzw.doodle.DoodlePen;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RevisePlayActivity extends AppCompatActivity  implements View.OnClickListener{

    private static final int HANDLER_AGAIN_RECORD_OR_PLAY= 904;
    private static final int handler_time_pre = 30;
    private float handler_time_scale = 1;
    private boolean isEraser = false;
    private boolean isWhiteboard = false;
    private boolean isGliding = false;
    private int mWhiteboardMaxPage = 10;
    private boolean isLargeJumping = false;
    private int fl_width;
    private int fl_height;

    private Disposable disposable;

    protected PowerManager.WakeLock wakeLock;

    private String voiceFilePath;

    private PlayServiceConnection mPlayServiceConnection;
    private PlayService_2.PlayBinder playBinder;
    private PlayService_2 playService;
    private int mDuration;

    private int mDoodleImageIndex = 0;
    private List<String> mDoodleImagePath = new ArrayList<>();
    private List<Bitmap> mDoodle_bitmap_list = new ArrayList<>();
    private List<DoodleParams> mDoodleParams_list = new ArrayList<>();
    private List<IDoodle> mDoodle_list = new ArrayList<>();
    private List<DoodleView> mDoodleView_list = new ArrayList<>();
    private List<DoodleOnTouchGestureListener> mDoodleTouchGestureListener_list = new ArrayList<>();

    private int mWhiteboard_DoodleImageIndex = 0;
    private String mWhiteboard_DoodleImagePath;
    private Bitmap mWhiteboard_Doodle_bitmap;
    private List<DoodleParams> mWhiteboard_DoodleParams_list = new ArrayList<>();
    private List<IDoodle> mWhiteboard_Doodle_list = new ArrayList<>();
    private List<DoodleView> mWhiteboard_DoodleView_list = new ArrayList<>();
    private List<DoodleOnTouchGestureListener> mWhiteboard_DoodleTouchGestureListener_list = new ArrayList<>();


    private String trackFilePath;
    private int trackId = 0;
    private List<TrackBean> trackBeanList = new ArrayList<>();
    private int trackIndex_prev = 0;
    private int trackIndex_next = 0;
    private int playCurrentPosition_prev = 0;
    private int playCurrentPosition_next = 0;
    private int largeJumpTime = 0;
    private int largeJumpCount = 0;
    private MyHandler handler;
    private String videoUrl;

    private boolean isDowningTxt;

    FrameLayout flDoodle;
    Button ivPlayState;
    Button btn_fastForward_1_0;
    Button btn_fastForward_2_0;
    TextView tvTime;


    static class MyHandler extends Handler {
        WeakReference<RevisePlayActivity> weakReference;

        public MyHandler(RevisePlayActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (weakReference.get() == null) {
                return;
            }
            RevisePlayActivity activity = weakReference.get();
            if (msg.what == HANDLER_AGAIN_RECORD_OR_PLAY) {
                if (activity.isLargeJumping) {
                    return;
                }
                if (msg.arg1 == 2) {
                    activity.callPlayMusic();
                    activity.drawTrack_rxJava();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.education_activity_revise_play);
        flDoodle = findViewById(R.id.fl_doodle);
        ivPlayState = findViewById(R.id.iv_play_state);
        ivPlayState.setOnClickListener(this);
        btn_fastForward_1_0 = findViewById(R.id.btn_fastForward_1_0);
        btn_fastForward_1_0.setOnClickListener(this);
        btn_fastForward_2_0 = findViewById(R.id.btn_fastForward_2_0);
        btn_fastForward_2_0.setOnClickListener(this);
        tvTime = findViewById(R.id.tv_time);



        initData();
    }

    protected void initData() {
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "voice");

        handler = new MyHandler(this);

        downloadVideo(videoUrl);
        getWhiteboardPic();

        Intent bindIntent = new Intent(this, PlayService_2.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(bindIntent, mPlayServiceConnection, Context.BIND_AUTO_CREATE);
        ComUtil.setWindowEpdMode(this, 0);


    }

    private void downloadVideo(String videoUrl) {
        //trackFilePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/track.txt";
        trackFilePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/test_t_1.txt";
        //voiceFilePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/11.mp3";
        voiceFilePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/test_m_1.mp3";
        //voiceFilePath = "http://newpage-test.oss-cn-hangzhou.aliyuncs.com/2020-11-26/7209_1659_192836_video_1606372714585.mp3";
        //voiceFilePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/7248_1717_193246_video_1606469890961.mp3";
        //voiceFilePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/7248_1717_193245_video_1606468964488.mp3";

        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/test_p_0.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/test_p_1.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/test_p_2.png");
        /*mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_0.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_1.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_2.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_3.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_4.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_6.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_7.png");*/
    }

    private void getWhiteboardPic() {
        flDoodle.post(new Runnable() {
            @Override
            public void run() {
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtil.i("-----doodle----getWhiteboardPic主线程ID: "+thread1.getName() );
                LogUtil.i("-----doodle----getWhiteboardPic当前线程ID: "+thread2.getName() );

                fl_width = flDoodle.getMeasuredWidth();
                fl_height = flDoodle.getMeasuredHeight();
                LogUtil.i("fl_doodle的宽：" + fl_width + ", 高" + fl_height);

                flDoodle.destroyDrawingCache();
                flDoodle.setDrawingCacheEnabled(true);
                flDoodle.buildDrawingCache();
                Bitmap bitmap = flDoodle.getDrawingCache();
                mWhiteboard_Doodle_bitmap = bitmap.copy(bitmap.getConfig(), false);
                if(mWhiteboard_Doodle_bitmap == null) {
                    LogUtil.e("出错了：复制位图失败");
                    finish();
                    return;
                }

                lineReadFile();
                downLoadImg(false);
            }
        });
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        callStopMusic();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        rxjava_disposable();
        if (mPlayServiceConnection != null) {
            unbindService(mPlayServiceConnection);
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        ComUtil.setWindowEpdMode(this, -1);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_play_state:{
                if (playBinder != null) {
                    if (isLargeJumping || isGliding || isDowningTxt) {
                        return;
                    }
                    if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_IDE) {
                        callPlayMusic();
                    } else if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_COMPLETE) {
                        again_recording_or_play();
                    } else if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY) {
                        callPauseMusic();
                    } else if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE) {
                        callResumeMusic();
                    }
                }
            }break;
            case R.id.btn_fastForward_1_0:{
                callPlaySpeed(1.0f);
            }break;
            case R.id.btn_fastForward_2_0:{
                callPlaySpeed(2.0f);
            }break;

        }

    }

    private void again_recording_or_play() {
        handler_time_scale = 1;
        isEraser = false;
        isWhiteboard = false;
        isGliding = false;
        isLargeJumping = false;
        isDowningTxt = false;

        flDoodle.removeAllViews();

        if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
                || playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
        ) {
            playBinder.callStopMusic();
        } else if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_COMPLETE) {
            playBinder.callSetPlayStatus(PlayService_2.STATUS_MUSIC_IDE);
        }
//        mDuration = 0;

        mDoodleImageIndex = 0;
        mDoodle_bitmap_list = new ArrayList<>();
        mDoodleParams_list = new ArrayList<>();
        mDoodle_list = new ArrayList<>();
        mDoodleView_list = new ArrayList<>();
        mDoodleTouchGestureListener_list = new ArrayList<>();

        mWhiteboard_DoodleImageIndex = 0;
        //mWhiteboard_Doodle_bitmap = null;
        mWhiteboard_DoodleParams_list = new ArrayList<>();
        mWhiteboard_Doodle_list = new ArrayList<>();
        mWhiteboard_DoodleView_list = new ArrayList<>();
        mWhiteboard_DoodleTouchGestureListener_list = new ArrayList<>();

        //trackBeanList = new ArrayList<>();
        trackIndex_prev = 0;
        trackIndex_next = 0;
        playCurrentPosition_prev = 0;
        playCurrentPosition_next = 0;
        largeJumpTime = 0;

        downLoadImg(false);

        Message msg = handler.obtainMessage();
        msg.what = HANDLER_AGAIN_RECORD_OR_PLAY;
        msg.arg1 = 2;
        handler.sendMessageDelayed(msg, 500);
    }

    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            playBinder = (PlayService_2.PlayBinder) binder;
            String testData = playBinder.getServiceTestData();
        
            playService = playBinder.getService();
            setPlayMusicUrl(voiceFilePath);
            playService.setCallback(new PlayService_2.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {
     
                }

                @Override
                public void onMusicStausChange(final int status) {
                    //setPlayView(status);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.i("播放状态：" + status);
                            showMusicStatus();
                        }
                    });
                }

                @Override
                public void onCurrentPosition(final int currentPosition, final int duration) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.i("播放时间：" + currentPosition + "/" + duration);
//                            tv_playTime.setText(currentPosition + "/" + duration);
                            tvTime.setText(currentPosition + "/" + duration);
                            playCurrentPosition_next = currentPosition;
                            if (playBinder != null) {
                                if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY) {
                                } else {
                                    if (currentPosition == 0) {
                                        if (duration != 0) {
                                            mDuration = duration;
                                        }
                                    }
                                }
                            }
                        }
                    });
                }

                @Override
                public void OnDuration(int duration) {
                    LogUtil.i("总时长：" + duration);
                }

                @Override
                public void onCompletion() {
                    delay_rxjava_disposable();
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    private void setPlayMusicUrl(String url) {
        if (playBinder != null) {
            playBinder.callSetmUrl(url);
        }
    }

    private void callPlayMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_IDE
                    || playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_COMPLETE
            ) {
                playBinder.callPlayMusic();
                setButtonPauseImage();
            }
        }
    }

    private void setButtonPlayImage() {
        ivPlayState.setText("播放");
    }

    private void setButtonPauseImage() {
        ivPlayState.setText("暂停");
    }

    private void callPauseMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
            ) {
                playBinder.callPauseMusic();
                setButtonPlayImage();
            }
        }
    }

    private void callResumeMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callResumeMusic();
                setButtonPauseImage();
            }
        }
    }

    private void callStopMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
                    || playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callStopMusic();
                delay_rxjava_disposable();
                setButtonPlayImage();
            }
        }
    }

    private void callPlaySpeed(float speed) {
        if (isLargeJumping) {
            return;
        }
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
            ) {
                handler_time_scale = speed;
                playBinder.callPlaySpeed(speed);
                rxjava_disposable();
                drawTrack_rxJava();
            }
        }
    }

    private void callSeekTo(int position) {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callSeekTo(position);
            }
        }
    }

    private void showMusicStatus() {
        if (playBinder != null) {
            switch (playBinder.callPlayStatus()) {
                case PlayService_2.STATUS_MUSIC_IDE_PRE: {
//                    tv_playStatus.setText("初始化之前");
                }
                break;
                case PlayService_2.STATUS_MUSIC_IDE: {
//                    tv_playStatus.setText("初始化");
                }
                break;
                case PlayService_2.STATUS_MUSIC_PLAY: {
                    LogUtil.i("播放");
                    setButtonPauseImage();
                }
                break;
                case PlayService_2.STATUS_MUSIC_PAUSE: {
                    LogUtil.i("暂停");
                    setButtonPlayImage();
                }
                break;
                case PlayService_2.STATUS_MUSIC_STOP: {
                    LogUtil.i("停止");
                    setButtonPlayImage();
                }
                break;
                case PlayService_2.STATUS_MUSIC_COMPLETE: {
                    LogUtil.i("播放完成");
                    setButtonPlayImage();
                }
                break;
            }
        }
    }

    private void downLoadImg(final boolean isPlay) {
        final String f_url = isWhiteboard ? mWhiteboard_DoodleImagePath : mDoodleImagePath.get(mDoodleImageIndex);
        isGliding = true;
        Glide.with(this).asBitmap().load(f_url).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        isGliding = false;
                        Thread thread1 = getMainLooper().getThread();
                        Thread thread2 = Thread.currentThread();

                        LogUtil.i("-----doodle----glide主线程ID: " + thread1.getId());
                        LogUtil.i("-----doodle----glide当前线程ID: " + thread2.getId());

                        LogUtil.i("Glde图片-成功 url = " + f_url);
                        if (isWhiteboard) {
                            mWhiteboard_Doodle_bitmap = resource;
                        } else {
                            mDoodle_bitmap_list.add(resource);
                        }

                        initDoodleData(isPlay);
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        isGliding = false;
                        LogUtil.e("Glde图片-失败 url = " + f_url);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }


    private void initDoodleData(boolean isPlay) {
        //fl_doodle.removeAllViews();
        DoodleParams mDoodleParams = new DoodleParams();
        mDoodleParams.mSavePathIsDir = false;
        mDoodleParams.mIsDrawableOutside = false;


        /*
        Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级
         */

        IDoodle mDoodle = null;
        DoodleView mDoodleView = null;
        mDoodle = mDoodleView = new DoodleViewWrapper(this, isWhiteboard ? mWhiteboard_Doodle_bitmap : mDoodle_bitmap_list.get(mDoodleImageIndex), mDoodleParams.mOptimizeDrawing, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap bitmap, Runnable callback) { // 保存图片为jpg格式
                LogUtil.i("-----doodle----onSaved");
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtil.i("-----doodle----doodleViewWrapper主线程ID: "+thread1.getId() );
                LogUtil.i("-----doodle----doodleViewWrapper当前线程ID: "+thread2.getId() );
            }

            @Override
            public void onReady(IDoodle doodle) {
                LogUtil.i("-----doodle----onReady");
            }
        });

        DoodleOnTouchGestureListener mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {

                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {

            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {

            }

            @Override
            public void onCallScrollBegin(MotionEvent e) {

            }

            @Override
            public void onCallScrollEnd(MotionEvent e) {

            }

            @Override
            public void onCallScroll(MotionEvent e) {

            }
        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
            }
        };

        mTouchGestureListener.setSupportScale(false); //禁止放大缩小

        mTouchGestureListener.setSupportDoodle(false); //禁止涂鸦

        mTouchGestureListener.setTouchType(DoodleOnTouchGestureListener.TOUCH_TYPE_ALL);
        IDoodleTouchDetector detector = new DoodleTouchDetector(getApplicationContext(), mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);

        mDoodle.setIsDrawableOutside(mDoodleParams.mIsDrawableOutside);
        flDoodle.addView(mDoodleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mDoodle.setDoodleMinScale(mDoodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(mDoodleParams.mMaxScale);
        //mDoodle.setSize(2);

        if(isWhiteboard) {
            mWhiteboard_DoodleParams_list.add(mDoodleParams);
            mWhiteboard_Doodle_list.add(mDoodle);
            mWhiteboard_DoodleView_list.add(mDoodleView);
            mWhiteboard_DoodleTouchGestureListener_list.add(mTouchGestureListener);
        } else {
            mDoodleParams_list.add(mDoodleParams);
            mDoodle_list.add(mDoodle);
            mDoodleView_list.add(mDoodleView);
            mDoodleTouchGestureListener_list.add(mTouchGestureListener);
        }

        if(isPlay) {
            drawTrack_rxJava();
        }
    }

    /**
     * 包裹DoodleView，监听相应的设置接口，以改变UI状态
     */
    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, Bitmap bitmap, boolean optimizeDrawing, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, listener);
        }
    }

    private void switchPage(final boolean isNext, final boolean isPlay) {
        if (isGliding) {
            LogUtil.i("正在加载图片，请稍后");
            return;
        }
        if (isPlay) {
            rxjava_disposable();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchPage_real(isNext, isPlay);
            }
        });
    }

    private void switchPage_real(boolean isNext, boolean isPlay) {
        if (isNext) {
            if (isWhiteboard) {
                if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size() - 1
                        && mWhiteboard_DoodleView_list.size() >= mWhiteboardMaxPage) {
                    LogUtil.i("已经是最后一页，无法下一页");
                    return;
                }
            } else {
                if (mDoodleImageIndex >= mDoodleImagePath.size() - 1) {
                    LogUtil.i("已经是最后一页，无法下一页");
                    return;
                }
            }
            if (isWhiteboard) {
                mWhiteboard_DoodleImageIndex++;
            } else {
                mDoodleImageIndex++;
            }
        } else {
            if (isWhiteboard) {
                if (mWhiteboard_DoodleImageIndex == 0) {
                    LogUtil.i("已经是第一页，无法上一页");
                    return;
                }
            } else {
                if (mDoodleImageIndex == 0) {
                    LogUtil.i("已经是第一页，无法上一页");
                    return;
                }
            }

            if (isWhiteboard) {
                mWhiteboard_DoodleImageIndex--;
            } else {
                mDoodleImageIndex--;
            }
        }
        if (isWhiteboard) {
            for (int i = 0; i < mWhiteboard_DoodleView_list.size(); i++) {
                mWhiteboard_DoodleView_list.get(i).setVisibility(View.GONE);
                mWhiteboard_DoodleTouchGestureListener_list.get(i).setSupportDoodle(false); //禁止涂鸦
            }
            if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size()) {
                initDoodleData(isPlay);
            } else {
                mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.VISIBLE);
                if (isPlay) {
                    drawTrack_rxJava();
                }

            }
        } else {
            for (int i = 0; i < mDoodleView_list.size(); i++) {
                mDoodleView_list.get(i).setVisibility(View.GONE);
                mDoodleTouchGestureListener_list.get(i).setSupportDoodle(false); //禁止涂鸦
            }
            if (mDoodleImageIndex >= mDoodleView_list.size()) {
                downLoadImg(isPlay); //这个函数中也有drawTrack_pub();
            } else {
                mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.VISIBLE);
                if (isPlay) {
                    drawTrack_rxJava();
                }

            }
        }
    }

    private void switchWhiteboard(final boolean isPlay) {
        if (isGliding) {
            LogUtil.i("正在加载图片，请稍后");
            return;
        }
        if (isPlay) {
            rxjava_disposable();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchWhiteboard_real(isPlay);
            }
        });
    }

    private void switchWhiteboard_real(boolean isPlay) {
        isWhiteboard = !isWhiteboard;
        if (isWhiteboard) {
            mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.GONE);
            mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(false); //禁止涂鸦
            if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size()) {
                initDoodleData(isPlay);
            } else {
                mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.VISIBLE);
                if (isPlay) {
                    drawTrack_rxJava();
                }
            }
        } else {
            mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.GONE);
            mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(false); //禁止涂鸦

            mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.VISIBLE);
            if (isPlay) {
                drawTrack_rxJava();
            }
        }
    }

    private void lineReadFile() {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                try {
                    trackBeanList.clear();
                    trackIndex_prev = 0;
                    trackIndex_next = 0;
                    FileReader fr = new FileReader(trackFilePath);
                    BufferedReader br = new BufferedReader(fr);
                    String line = "";

                    while ((line = br.readLine()) != null && !"".equals(line.trim())) {
                        TrackBean trackBean = JsonUtils.fromJson(line, TrackBean.class);
                        if (trackBean == null) continue;
                        trackBeanList.add(trackBean);
                    }
                    //LogUtil.i(trackBeanList.toString());
                    br.close();
                    fr.close();
                    //testTrackEvent();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    emitter.onError(new Throwable("读取轨迹文件失败！！" + e.getMessage()));
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(new Throwable("读取轨迹文件失败！！" + e.getMessage()));
                    emitter.onComplete();
                } finally {
                    emitter.onNext(true);
                    emitter.onComplete();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                playBinder.callPlayMusic();
                LogUtil.i("读取文件成功");
                drawTrack_rxJava();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void drawTrack_real() {
        if (trackIndex_prev >= trackBeanList.size()) {
            LogUtil.i("出错了：trackIndex_prev >= trackBeanList.size()");
            rxjava_disposable();
            return;
        }
        TrackBean trackBean = trackBeanList.get(trackIndex_prev);
        trackIndex_prev++;
        //LogUtil.i("测试16--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
        //LogUtil.i(trackBean.toString());
        float f_scale_w = 0;
        float f_scale_h = 0;
        float f_scale = 0;
        if (trackBean.getFl_width() == 0) {
            f_scale_w = 0;
        } else {
            f_scale_w = 1.0f * fl_width / trackBean.getFl_width();
        }

        if (trackBean.getFl_height() == 0) {
            f_scale_h = 0;
        } else {
            f_scale_h = 1.0f * fl_height / trackBean.getFl_height();
        }

        //LogUtil.e("录制UI和播放UI的宽比：" + f_scale_w + "，高比：" + f_scale_h);
        if (f_scale_w == 0 || f_scale_h == 0) {
            f_scale = 1;
        } else {
            if (f_scale_w - f_scale_h > 0) {
                f_scale = f_scale_h;
            } else {
                f_scale = f_scale_w;
            }
        }


        if ("ACTION_DOWN".equals(trackBean.getAction())) {
            if (isWhiteboard) {
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onDown(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onScrollBegin(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onDown(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onScrollBegin(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            }

        } else if ("ACTION_MOVE".equals(trackBean.getAction())) {
            LogUtil.i("ACTION_MOVE.equals(trackBean.getAction())");
            if (isWhiteboard) {
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onScroll(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onScroll(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            }

        } else if ("ACTION_UP".equals(trackBean.getAction())) {
            if (isWhiteboard) {
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onScrollEnd(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onScrollEnd(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            }

        } else if ("ACTION_PEN_ERASER".equals(trackBean.getAction())) {
            if (isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.ERASER);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.ERASER);
            }

        } else if ("ACTION_PEN_BRUSH".equals(trackBean.getAction())) {
            if (isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.BRUSH);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.BRUSH);
            }

        } else if ("ACTION_PREV_PAGE".equals(trackBean.getAction())) {
            LogUtil.i("播放轨迹上一页：" + trackBean.getId());
            switchPage(false, true);
        } else if ("ACTION_NEXT_PAGE".equals(trackBean.getAction())) {
            LogUtil.i("播放轨迹下一页：" + trackBean.getId());
            switchPage(true, true);
        } else if ("ACTION_SWITCH_WHITEBOARD".equals(trackBean.getAction())) {
            LogUtil.i("切换白板：" + trackBean.getId());
            switchWhiteboard(true);
        } else if ("ACTION_UNDO".equals(trackBean.getAction())) {
            drawTrack_undo(true);
        } else if ("ACTION_REDO".equals(trackBean.getAction())) {
            drawTrack_undo(false);
        }
    }

    private void drawTrack_undo(boolean isUn) {
        if (isUn) {
            if (isWhiteboard) {
                if (!mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).undo()) {
                    LogUtil.i("无法再撤销");
                }
            } else {
                if (!mDoodle_list.get(mDoodleImageIndex).undo()) {
                    LogUtil.i("无法再撤销");
                }
            }

        } else {
            if (isWhiteboard) {
                if (!mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).redo(1)) {
                    LogUtil.i("无法再反撤销");
                }
            } else {
                if (!mDoodle_list.get(mDoodleImageIndex).redo(1)) {
                    LogUtil.i("无法再反撤销");
                }
            }
        }
    }

    private void drawTrack_rxJava() {
        rxjava_disposable();

        Observable.interval(handler_time_pre * 10, (int) (handler_time_pre / handler_time_scale), TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.single())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        //LogUtil.i("测试1");
                        /*if(isPx30Eink) {
                            drawTrack_rxJava_next();
                        } else {*/
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                drawTrack_rxJava_next();
                            }
                        });
                        //}
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void drawTrack_rxJava_next() {
        if (isGliding) {
            return;
        }
        //LogUtil.i("测试2--trackIndex_prev = " + trackIndex_prev + ", trackIndex_next = " + trackIndex_next);
        if (trackIndex_prev == trackIndex_next) {
            int next_time = 0;
            if (isLargeJumping) {
                next_time = largeJumpTime;
            } else {
                next_time = playCurrentPosition_next;
            }
            final int seekTime = next_time;
//            LogUtil.i("测试3--next_time = " +next_time + ", playCurrentPosition_prev = " + playCurrentPosition_prev);
            if (playCurrentPosition_prev <= next_time) {
                LogUtil.i("测试4--trackBeanList.size() = " + trackBeanList.size());
                if (trackIndex_next < trackBeanList.size()) {
//                    LogUtil.i("测试5");
                    String action = "";
                    for (int i = trackIndex_next; i < trackBeanList.size(); i++) {
                        //LogUtil.i("测试6");
                        TrackBean trackBean = trackBeanList.get(i);
                        if (trackBean.getTime() <= next_time) {
                            trackIndex_next = i + 1;
                            action = trackBean.getAction();
                            LogUtil.i("测试7--trackIndex_next = " + trackIndex_next);
                        } else if ("ACTION_DOWN".equals(action) || "ACTION_MOVE".equals(action)) {
                            trackIndex_next = i + 1;
                            action = trackBean.getAction();
                            LogUtil.i("测试8--trackIndex_next = " + trackIndex_next);
                        } else {
                            LogUtil.i("测试9");
                            break;
                        }
                    }
                }
            }
//            LogUtil.i("测试10--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
            if (trackIndex_prev == trackIndex_next) {
                LogUtil.i("测试11");
                if (isLargeJumping) {
                    LogUtil.i("测试17");
                    isLargeJumping = false;
                    largeJumpCount = 0;
                    handler_time_scale = 1;
                    rxjava_disposable();
                    drawTrack_rxJava();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callSeekTo(seekTime);
                            callResumeMusic();
                        }
                    });
                }
                if (trackIndex_next == trackBeanList.size()) {
                    LogUtil.i("测试12");
                    rxjava_disposable();
                }
                return;
            } else {
                if (trackIndex_next >= trackBeanList.size()) {
                    playCurrentPosition_prev = mDuration;
                } else {
                    playCurrentPosition_prev = trackBeanList.get(trackIndex_next).getTime();
                }

                LogUtil.i("测试14--playCurrentPosition_prev = " + playCurrentPosition_prev);
            }
        }
//        LogUtil.i("测试15--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
        if (trackIndex_prev > trackIndex_next) {
            LogUtil.e("出错了，trackIndex_prev > trackIndex_next");
            rxjava_disposable();
            return;
        }
//        LogUtil.i("线程时间：" + (System.currentTimeMillis() - PlayService_2.testTime_2) + ", 线程名：" + Thread.currentThread().getName());
        //PlayService_2.testTime_2 = System.currentTimeMillis();
        if (trackIndex_prev >= trackBeanList.size()) {
            rxjava_disposable();
        }
        drawTrack_real();
    }

    private void rxjava_disposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    private void delay_rxjava_disposable() {
        Observable.just(1)
                .delay(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        rxjava_disposable();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void delay_largeJumpCountMax() {
        Observable.just(1)
                .delay(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        drawTrack_rxJava_next();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}
